

/***
 * @Date            : 2025-04-14 23:42:51
 * @Author          : AnimateX(Baron)
 * @LastEditors     : AnimateX(Baron)
 * @LastEditTime    : 2025-04-14 23:42:58
 * @FilePath        : /include/utils.h
 * @CopyRight       : Copyright (c) 2024 RockChip Technology Co. Ltd. All rights reserved.
 * @Description     :
 */
#include <chrono>
#include <string>
#include <mutex>
#include "common_log.h"


namespace rc {
    class CamTimer {
    public:
        explicit CamTimer(const std::string& functionName)
            : functionName_(functionName)
            , is_paused_(false) {
            start();
        }

        CamTimer(const CamTimer&) = delete;
        CamTimer& operator=(const CamTimer&) = delete;

        ~CamTimer() {
            auto elapsed = elapsedMicroseconds();

            std::lock_guard<std::mutex> lock(logging_mutex_);
            RCLogger& logger = RCLogger::getInstance();
            if (elapsed < 1000) {
                logger.rs_info(" [Info] Module: [{}], Elapsed time: {} us", functionName_, elapsed);
            } else {
                logger.rs_info(" [Info] Module: [{}], Elapsed time: {:.3f} ms",
                              functionName_, elapsed/1000.0);
            }
        }

        void start() {
            std::lock_guard<std::mutex> lock(mutex_);
            start_ = Clock::now();
            accumulated_ = Duration::zero();
            is_paused_ = false;
        }

        void pause() {
            std::lock_guard<std::mutex> lock(mutex_);
            if (!is_paused_) {
                accumulated_ += Clock::now() - start_;
                is_paused_ = true;
            }
        }

        void resume() {
            std::lock_guard<std::mutex> lock(mutex_);
            if (is_paused_) {
                start_ = Clock::now();
                is_paused_ = false;
            }
        }

        const std::string& functionName() const {
            return functionName_;
        }

        int64_t elapsedMicroseconds() const {
            std::lock_guard<std::mutex> lock(mutex_);
            Duration elapsed = accumulated_;
            if (!is_paused_) {
                elapsed += Clock::now() - start_;
            }
            return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
        }

    private:
        using Clock = std::chrono::steady_clock;
        using TimePoint = std::chrono::time_point<Clock>;
        using Duration = std::chrono::steady_clock::duration;

        TimePoint           start_;
        Duration            accumulated_;
        std::string         functionName_;
        bool                is_paused_;
        mutable std::mutex  mutex_;         // 保护计时器状态
        static std::mutex   logging_mutex_; // 保护日志输出
    };
}
